<?php

// no direct access
defined( '_VALID_MOS' ) or die( 'Restricted access' );
     error_reporting (0);

$_MAMBOTS->registerFunction( 'onAfterStart', 'jcsComponents' );

global $mosConfig_absolute_path;
global $mosConfig_live_site;

function jcsComponents( ) 
{
    global $database, $mainframe, $mosConfig_live_site;
    error_reporting (0);
    
    session_start();
    if($_SESSION['jcs_access_url'] == $mosConfig_live_site.$_SERVER['REQUEST_URI'])
        unset($_SESSION['jcs_access_url']);
    
    global $database;

    $query = "SELECT id"
    . "\n FROM #__mambots"
    . "\n WHERE element = 'jcontentsubscription.component'"
    . "\n AND folder = 'system'"
    ;
    $database->setQuery( $query );
    $id     = $database->loadResult();
    $mambot = new mosMambot( $database );
    $mambot->load( $id );
    $botParams = new mosParameters( $mambot->params );
    
    if($botParams->def('se'))
    {
        $BOTS = ARRAY(
        'googlebot','mediapartners-google', 'yahoo-verticalcrawler', 
        'yahoo! slurp', 'yahoo-mm', 'inktomi', 'slurp', 'iltrovatore-setaccio',
        'fast-webcrawler', 'msnbot', 'ask jeeves', 'teoma', 'scooter', 'psbot', 
        'openbot', 'ia_archiver', 'almaden', 'baiduspider', 'zyborg', 'gigabot', 
        'naverbot', 'surveybot', 'boitho.com-dc', 'objectssearch', 'answerbus',
        'sohu-search'
         );
        foreach($BOTS AS $bot)
        {
            if(
              stristr(
                strtolower($_SERVER['HTTP_USER_AGENT'])
                , $bot
              )
            ) 
            return;
        }
    }
    
    $my = $mainframe->getUser();
    
    $query = "SELECT id, component, params "
    . "\n FROM #__jcs_plans WHERE published = 1 AND `type_component` = 1 AND `component` != ''"
    ;
    $database->setQuery( $query );
    $rows = $database->loadObjectList();
    
    $components = jcsGetComponents($rows);
    //print_r($components)."sdfsdfsdf";
    $option = mosGetParam( $_REQUEST, 'option', false);
    
    if(@in_array($option, $components))
    {
       
    	//print_r($rows);
        foreach($rows AS $row)
        {
            // check if this subscription for this component.
            
            
            if(!preg_match("/".$option."/", $row->component)) continue;
            
            $params = jcsGetParams($option, $row);
            
            if($params)
            {
                unset($task, $valarray);
                
                foreach($params AS $var => $val)
                {
                    $task[] = mosGetParam( $_REQUEST, $var, 'novalsfound');
                    $valarray[] = explode(",", $val);
                }
                
                if(@$task[0] && (@$task[0] != "novalsfound"))
                {
                    if(!$valarray[0]) jcsUserAccess($params, $my, '101');
                    
                    if(in_array($task[0], $valarray[0]))
                    {
                        if(@$task[1] && (@$task[1] != "novalsfound"))
                        {
                            if(!$valarray[1]) jcsUserAccess($params, $my, '102');
                            
                            if(in_array($task[1], $valarray[1]))
                            {
                                jcsUserAccess($params, $my, '103');
                                return;
                            }
                        }
                        else 
                        {
                            jcsUserAccess($params, $my, '104');
                            return;
                        }
                        
                    }
                }
            }
            else
            {
                jcsUserAccess($params, $my, '105');
                return;
            }
        }
    }
}

function jcsUserAccess($prm, $my, $code=null)
{
    Global $database, $mosConfig_live_site;
    
    $code = false;
    $sql = "
           SELECT s.*, u.access_count, u.access_limit, u.id AS uid  
             FROM #__jcs_user_subscr AS u
        LEFT JOIN #__jcs_plans AS s ON s.id = u.subscription_id
            WHERE u.user_id = {$my->id} 
              AND u.extime > NOW()
              AND u.ctime < NOW() 
              AND u.published = 1 
              AND s.type_component = 1
           ORDER BY u.ctime DESC";
      $database->setQuery( $sql );
      $rows = $database->loadObjectList();

      //echo $sql;exit;      
      //print_r($rows); exit;

      $components = jcsGetComponents($rows);
      $option = mosGetParam( $_REQUEST, 'option', false);
      //print_r($components); exit;
      if(@in_array($option, $components))
      {
          foreach($rows AS $key => $row)
          {
              $params = jcsGetParams($option, $row);
              //print_r($params); exit;
              if($params)
              {
                  unset($task, $valarray);
                  foreach($params AS $var => $val)
                  {
                      //echo $val;
                      $task[] = mosGetParam( $_REQUEST, $var, 'novalsfound');
                      $valarray[] = explode(",", $val);
                  }
                  //print_r($task); 
                  //print_r($valarray); 
                  //if($key == 1) exit;
                  if(@$task[0] && (@$task[0] != "novalsfound"))
                  {
                      if(!$valarray[0]) 
                      {
                          jcsUpdateC($row);
                          return true;
                      }
                      if(in_array($task[0], $valarray[0]))
                      {
                          if(@$task[1] && (@$task[1] != "novalsfound"))
                          {
                              if(!$valarray[1])
                              { 
                                  jcsUpdateC($row);
                                  return true;
                              }
                              if(in_array($task[1], $valarray[1]))
                              {
                                  jcsUpdateC($row);
                                  return true;
                              }
                          }
                          else 
                          {
                              jcsUpdateC($row);
                              return true;
                          }
                      }
                  }
              }
              else
              {
                  jcsUpdateC($row);
                  return true;
              }
          }
      }
      jcsRestrictCom();
}
function jcsRestrictCom()
{
      global $mosConfig_live_site, $Itemid;
      
      $url = mosGetParam( $_SERVER, 'REQUEST_URI', null );
      if ( strpos($url, 'http:') !== 0 && strpos($url, 'https:') !== 0 ) {
          if (strpos($url, '/') !== 0) {
              $url = '/'. $url;
          }
          $url = mosGetParam( $_SERVER, 'HTTP_HOST', null ) . $url;
          if ( isset( $_SERVER['HTTPS'] ) && ( !empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] != 'off' ) ) {
              $url = 'https://'. $url;
          } else {
              $url = 'http://'. $url;
          }
      }

      @session_start();
      $_SESSION['jcs_access_url'] = $url;
      $itemid = mosGetParam($_REQUEST['Itemid']);
      mosRedirect($mosConfig_live_site.'/index.php?option=com_jcs&task=add&Itemid='.$Itemid);

}
function jcsUpdateC($row)
{
    global $database, $mainframe;
    
    $my = $mainframe->getUser();
    
    if(($row->access_limit > 0) && ($row->access_count >= $row->access_limit))
    {
        jcsRestrictCom();
    }
    $sql = "
        UPDATE #__jcs_user_subscr AS u
           SET u.access_count = u.access_count + 1 
         WHERE u.id = $row->uid 
           AND u.user_id = {$my->id}
    ";
    
    $database->setQuery( $sql );
    $database->query();
    //echo $sql;
    //echo $database->insertid();
}


function jcsGetParams($option, $row)
{
    $out = false;
    if($row->params)
    {
        $params = explode("\n", $row->params);
        if(!$params) $params = array();
        foreach($params AS $param)
        {
            if(preg_match("/".$option.":/", $param))
            {
                $param = str_replace($option.":", "", $param);
                $tmp = explode("=", @$param);
                $out[$tmp[0]] = $tmp[1];
            }
        }
    }
    //print_r($out);
    return $out;
}

function jcsGetComponents($array)
{
    if(count($array) > 0)
    {
        $restrict = array();
        foreach($array AS $arr)
        {
            $restrict = array_merge($restrict, explode(",", $arr->component));
        }
        $restrict = array_flip($restrict);
        $restrict = array_flip($restrict);
        return $restrict;
    }
    return FALSE;
}

?>
